package sys_serv

import (
	"strconv"
	"strings"
	"ubt-gin-admin/app/api/model/sys_mod"
	"ubt-gin-admin/app/pkg/db"
	"ubt-gin-admin/app/pkg/enums"
)

type sysBtn struct{}

var SysBtnServ = sysBtn{}

// Add 新增按钮
func (s *sysBtn) Add(req *sys_mod.SysBtnSaveReq) (string, string) {
	sqlStr := "INSERT INTO sys_button(btn_name, btn_code, sort, menu_id, states, add_time, upd_time) VALUES ($1, $2, $3, $4, 1, EXTRACT(epoch FROM NOW()), EXTRACT(epoch FROM NOW()))"
	return db.CudData(sqlStr, req.BtnName, req.BtnCode, req.Sort, req.MenuId)
}

// Exists 判断按钮编码是否存在
func (s *sysBtn) Exists(req *sys_mod.SysBtnExtVo) bool {
	sqlStr := "SELECT btn_id FROM sys_button WHERE states=1 AND menu_id=$1 AND btn_code=$2"
	param := make([]any, 0)
	param = append(param, req.MenuId)
	param = append(param, req.BtnCode)
	if req.BtnId != "" {
		sqlStr += " AND btn_id!=$3"
		param = append(param, req.BtnId)
	}
	if _, _, data := db.GetOne(sqlStr, param...); len(data) == 0 {
		return false
	}
	return true
}

// Update 修改按钮
func (s *sysBtn) Update(req *sys_mod.SysBtnSaveReq) (string, string) {
	sqlStr := "UPDATE sys_button SET btn_name=$1, btn_code=$2, sort=$3, menu_id=$4, upd_time=EXTRACT(epoch FROM NOW()) WHERE btn_id=$5"
	return db.CudData(sqlStr, req.BtnName, req.BtnCode, req.Sort, req.MenuId, req.BtnId)
}

// Deletes 删除按钮
func (s *sysBtn) Deletes(req *sys_mod.SysBtnDelsReq) (string, string) {
	var (
		param []any
		q     string
		n     = 0
	)
	idList := strings.Split(req.BtnIds, ",")
	for _, curId := range idList {
		n++
		q += "$" + strconv.Itoa(n) + ","
		param = append(param, curId)
	}
	q = q[:len(q)-1]
	sqlStr := "UPDATE sys_button SET states=2, upd_time=EXTRACT(epoch FROM NOW()) WHERE btn_id IN (" + q + ")"
	return db.CudData(sqlStr, param...)
}

// DelByMenu 根据菜单编号删除按钮
func (s *sysBtn) DelByMenu(ch chan int, menuIds string) {
	var (
		param []any
		q     string
		n     = 0
	)
	idList := strings.Split(menuIds, ",")
	for _, curId := range idList {
		n++
		q += "$" + strconv.Itoa(n) + ","
		param = append(param, curId)
	}
	q = q[:len(q)-1]
	sqlStr := "UPDATE sys_button SET states=2, upd_time=EXTRACT(epoch FROM NOW()) WHERE menu_id IN (" + q + ")"
	db.CudData(sqlStr, param...)
	<-ch
}

// One 获取按钮详情
func (s *sysBtn) One(btnId string) (string, string, map[string]any) {
	sqlStr := `SELECT a.btn_id, a.btn_name, a.btn_code, a.sort, a.menu_id, b.menu_name, b.menu_code, a.states, a.add_time, b.upd_time 
		FROM sys_button a 
		LEFT JOIN sys_menu b ON a.menu_id=b.menu_id 
		WHERE a.btn_id=$1`
	return db.GetOne(sqlStr, btnId)
}

// Count 获取按钮数量
func (s *sysBtn) Count(req *sys_mod.SysBtnPageReq) (string, string, any) {
	sqlStr := "SELECT COUNT(1) AS nums FROM sys_button WHERE states=1"
	param := make([]any, 0)
	var n = 0
	if req.Keywords != "" {
		sqlStr += " AND ("
		nameArr := strings.Split(req.Keywords, " ")
		for _, name := range nameArr {
			sqlStr += "btn_name LIKE '%'||$" + strconv.Itoa(n+1) + "||'%' OR " +
				"btn_code LIKE '%'||$" + strconv.Itoa(n+2) + "||'%' OR "
			param = append(param, name)
			param = append(param, name)
			n += 2
		}
		sqlStr = sqlStr[:len(sqlStr)-4]
		sqlStr += ")"
	}
	if req.MenuId != "" {
		sqlStr += " AND menu_id=$" + strconv.Itoa(n+1)
		param = append(param, req.MenuId)
		n++
	}
	if code, msg, data := db.GetOne(sqlStr, param...); len(data) > 0 && data["nums"].(int64) > 0 {
		return code, msg, data["nums"]
	}
	return enums.NoData.Code, enums.NoData.Msg, 0
}

// Page 获取按钮分页列表
func (s *sysBtn) Page(req *sys_mod.SysBtnPageReq) (string, string, any) {
	sqlStr := "SELECT a.btn_id, a.btn_name, a.btn_code, b.menu_name, b.menu_code, a.sort " +
		"FROM sys_button a " +
		"LEFT JOIN sys_menu b ON a.menu_id=b.menu_id " +
		"WHERE a.states=1"
	param := make([]any, 0)
	var n = 0
	if req.Keywords != "" {
		sqlStr += " AND ("
		nameArr := strings.Split(req.Keywords, " ")
		for _, name := range nameArr {
			sqlStr += "a.btn_name LIKE '%'||$" + strconv.Itoa(n+1) + "||'%' OR " +
				"a.btn_code LIKE '%'||$" + strconv.Itoa(n+2) + "||'%' OR "
			param = append(param, name)
			param = append(param, name)
			n += 2
		}
		sqlStr = sqlStr[:len(sqlStr)-4]
		sqlStr += ")"
	}
	if req.MenuId != "" {
		sqlStr += " AND a.menu_id=$" + strconv.Itoa(n+1)
		param = append(param, req.MenuId)
		n++
	}
	sqlStr += " ORDER BY a.btn_code LIMIT $" + strconv.Itoa(n+1) + " OFFSET $" + strconv.Itoa(n+2)
	param = append(param, req.Limit)
	param = append(param, req.Offset)
	return db.GetAll(sqlStr, param...)
}

// Select 获取按钮下拉列表
func (s *sysBtn) Select() (string, string, any) {
	sqlStr := "SELECT btn_id, btn_name, btn_code, menu_id, false AS chked FROM sys_button WHERE states=1 ORDER BY btn_code"
	if rows, err := db.Conn.Query(sqlStr); err == nil {
		bo := &sys_mod.SysBtnSelRes{}
		var bos []*sys_mod.SysBtnSelRes
		for rows.Next() {
			err = rows.Scan(&bo.BtnId, &bo.BtnName, &bo.BtnCode, &bo.MenuId, &bo.Chked)
			if err == nil {
				bos = append(bos, bo)
				bo = &sys_mod.SysBtnSelRes{}
			} else {
				return enums.SysErr.Code, enums.SysErr.Msg, nil
			}
		}
		return enums.Succeed.Code, enums.Succeed.Msg, bos
	}
	return enums.NoData.Code, enums.NoData.Msg, nil
}

// Sort 获取数量，用于排序
func (s *sysBtn) Sort(menuId string) (string, string, map[string]any) {
	sqlStr := "SELECT COUNT(1)+1 AS nums FROM sys_button WHERE states=1 AND menu_id=$1"
	return db.GetOne(sqlStr, menuId)
}
